package net.chrisrichardson.ec2deployer.applications;

import java.text.SimpleDateFormat
import net.chrisrichardson.ec2deployer.core.EC2Server
import net.chrisrichardson.ec2deployer.core.Application
import net.chrisrichardson.ec2deployer.util.FileUtil
import net.chrisrichardson.ec2deployer.cluster.WebServerTier;

class JmeterApplication extends Application {

  def webServerTier
  def runPrefix
  def jmxFileName

  JmeterApplication(EC2Server host, WebServerTier webServerTier) {
	  super(host)
	  def runPrefixFormat = new SimpleDateFormat("yyyyMMdd-HHmm");
	  this.runPrefix = runPrefixFormat.format(new Date());
	  this.webServerTier = webServerTier
  }
  
  def run(String jmxFileName, String prefix = "", List<Integer> threadCounts = [3], List<String> dataFiles=[]) {
	  for (int threadCount in threadCounts) {
	    runOnce(jmxFileName, prefix, threadCount, dataFiles)
	  }
  }

  def runOnce(String jmxFileName, String prefix, int threadCount, List<String> dataFiles) {
     host.scp(FileUtil.cygdrive(jmxFileName), "/tmp")
     dataFiles.each {host.scp(FileUtil.cygdrive(it), "/tmp")}
     def jmxFile = jmxFileName.substring(1 + jmxFileName.lastIndexOf("/"))
	 host.ssh("export PATH=\$PATH:\$JAVA_HOME/bin ; rm -f /tmp/foo.jtl ; /var/lib/jakarta-jmeter-2.2/bin/jmeter -n -t /tmp/$jmxFile -l /tmp/foo.jtl -Jiterations=100 -JthreadCount=$threadCount -Jhost=${webServerTier.privateDnsName} -Jport=${webServerTier.port}")
	 def localResults = "target/${runPrefix}-${prefix}-$threadCount-${host.instanceId}-foo.jtl"
  	 host.scpDown("/tmp/foo.jtl", localResults)
  	 localResults
  }


}